<template>
  <div style="height: 240px" ref="echart">
    echart
  </div>
</template>
<script>
//新版本的echarts引入方法
import * as echarts from 'echarts';
import { debounce } from 'common/utils'
export default {
  name: 'CommonEcharts',
  data() {
    return {
      echart: null,
      axisOption: {
        legend: {
          textStyle: {
            color: '#333'
          }
        },
        //图例
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: [],
          //x轴线
          axisLine: {
            lineStyle: {
              color: '#17b3a3'
            }
          },
          //x轴文字颜色
          axisLabel: {
            color: '#333'
          }
        },
        yAxis: [
          {
            type: 'value',
            axisLine: {
              //y轴线
              lineStyle: {
                color: '#17b3a3'
              }
            },
          }
        ],
        // 图标颜色
        color: ['#0f78f4','#dd536b','#9462e5','#a6a6a6','#e1bb22','#39c362','#3ed1cf'],
        series: []
      },
      normalOption: {
        color: ['#0f78f4','#dd536b','#9462e5','#a6a6a6','#e1bb22','#39c362','#3ed1cf'],
        tooltip: {
          trigger: 'item'
        },
        series: []
      },
    }
  },
  props: {
    chartData: {
      type: Object,
      default() {
        return {
          //1、先判断需要动态传入的参数
          xData: [],
          series: []
        }
      }
    },
    isAxisChart: {
      //2、是否是有坐标轴的图标，默认为真
      type: Boolean,
      default: true
    }
  },
  methods: {
    //初始化
    initChart() {
      this.initChartData()
      if(this.echart) {
        this.echart.setOption(this.options)
      } else {
        this.echart = echarts.init(this.$refs.echart)
        this.echart.setOption(this.options)
      }
    },
    initChartData() {
      if(this.isAxisChart) {
        this.axisOption.xAxis.data = this.chartData.xData
        this.axisOption.series = this.chartData.series
      } else {
        this.normalOption.series = this.chartData.series
      }
    },
    chartResize() {
      this.echart ? this.echart.resize() : ''
      console.log('缩放了');
    }
  },
  watch: {
    chartData: {
      handler: function() {
        this.initChart()
      },
      deep: true
    },
    isCollapse() {
      setTimeout(() => {
        this.chartResize()
      }, 300);
    }
  },
  mounted() {
    window.addEventListener('resize', debounce(this.chartResize))
  },
  //移除事件避免内存泄漏
  destroyed() {
    window.removeEventListener('resize', this.chartResize)
  },
  computed: {
    //3、通过计算属性决定返回的不同的对象
    options() {
      return this.isAxisChart ? this.axisOption : this.normalOption
    },
    isCollapse() {
      return this.$store.state.isCollapse
    }
  }
}
</script>